import { BaseStorage } from './base-storage.js';

/**
 * Cookie存储实现
 */
export class CookieStorage extends BaseStorage {
  constructor() {
    super('cookie');
  }

  /**
   * 检查Cookie是否可用
   * @returns {boolean} 是否可用
   */
  isAvailable() {
    return typeof document !== 'undefined' && document.cookie !== undefined;
  }

  /**
   * 设置Cookie
   * @param {string} key - 键名
   * @param {any} value - 值
   * @param {Object} options - 选项
   * @param {number} options.expires - 过期天数
   * @param {string} options.path - 路径
   * @param {string} options.domain - 域名
   * @param {boolean} options.secure - 是否安全
   * @param {string} options.sameSite - SameSite属性
   * @returns {boolean} 是否成功
   */
  set(key, value, options = {}) {
    if (!this.isAvailable()) {
      console.error('Cookie is not available');
      return false;
    }

    try {
      const {
        expires = 365,
        path = window.location.pathname || '/',
        domain = '',
        secure = false,
        sameSite = 'Lax'
      } = options;

      // 将值序列化为 JSON 字符串
      const serializedValue = JSON.stringify(value);
      let cookie = `${encodeURIComponent(key)}=${encodeURIComponent(serializedValue)}`;

      if (expires) {
        const date = new Date();
        date.setTime(date.getTime() + (expires * 24 * 60 * 60 * 1000));
        cookie += `; expires=${date.toUTCString()}`;
      }

      if (path) {
        cookie += `; path=${path}`;
      }

      if (domain) {
        cookie += `; domain=${domain}`;
      }

      if (secure) {
        cookie += '; secure';
      }

      if (sameSite) {
        cookie += `; samesite=${sameSite}`;
      }

      document.cookie = cookie;
      return true;
    } catch (e) {
      console.error('Error setting cookie:', e);
      return false;
    }
  }

  /**
   * 获取Cookie
   * @param {string} key - 键名
   * @param {Object} options - 选项
   * @returns {any|null} 值
   */
  get(key, options = {}) {
    if (!this.isAvailable()) {
      console.error('Cookie is not available');
      return null;
    }

    try {
      const name = `${encodeURIComponent(key)}=`;
      const decodedCookie = decodeURIComponent(document.cookie);
      const ca = decodedCookie.split(';');

      for (let i = 0; i < ca.length; i++) {
        let c = ca[i];
        while (c.charAt(0) === ' ') {
          c = c.substring(1);
        }
        if (c.indexOf(name) === 0) {
          const value = c.substring(name.length, c.length);
          // 尝试解析 JSON，如果失败则返回原始字符串
          try {
            return JSON.parse(value);
          } catch (e) {
            return value;
          }
        }
      }
      return null;
    } catch (e) {
      console.error('Error getting cookie:', e);
      return null;
    }
  }

  /**
   * 删除Cookie
   * @param {string} key - 键名
   * @param {Object} options - 选项
   * @param {string} options.path - 路径
   * @param {string} options.domain - 域名
   * @returns {boolean} 是否成功
   */
  remove(key, options = {}) {
    if (!this.isAvailable()) {
      console.error('Cookie is not available');
      return false;
    }

    try {
      const { 
        path = window.location.pathname || '/', 
        domain = '' 
      } = options;
      let cookie = `${encodeURIComponent(key)}=;expires=Thu, 01 Jan 1970 00:00:00 GMT`;

      if (path) {
        cookie += `; path=${path}`;
      }

      if (domain) {
        cookie += `; domain=${domain}`;
      }

      document.cookie = cookie;
      return true;
    } catch (e) {
      console.error('Error removing cookie:', e);
      return false;
    }
  }

  /**
   * 清空所有Cookie
   * @param {Object} options - 选项
   * @returns {boolean} 是否成功
   */
  clear(options = {}) {
    if (!this.isAvailable()) {
      console.error('Cookie is not available');
      return false;
    }

    try {
      const cookies = document.cookie.split(";");
      for (let i = 0; i < cookies.length; i++) {
        const cookie = cookies[i];
        const eqPos = cookie.indexOf("=");
        const name = eqPos > -1 ? cookie.substr(0, eqPos).trim() : cookie.trim();
        if (name) {
          // 解码键名
          const decodedName = decodeURIComponent(name);
          this.remove(decodedName, options);
        }
      }
      return true;
    } catch (e) {
      console.error('Error clearing cookies:', e);
      return false;
    }
  }

  /**
   * 获取所有Cookie键
   * @param {Object} options - 选项
   * @returns {string[]} 键数组
   */
  keys(options = {}) {
    if (!this.isAvailable()) {
      console.error('Cookie is not available');
      return [];
    }

    try {
      if (!document.cookie) return [];
      return document.cookie.split(';').map(cookie => {
        const eqPos = cookie.indexOf('=');
        if (eqPos > -1) {
          const key = cookie.substr(0, eqPos).trim();
          // 对键名进行 URL 解码
          return decodeURIComponent(key);
        }
        return cookie.trim();
      }).filter(key => key);
    } catch (e) {
      console.error('Error getting cookie keys:', e);
      return [];
    }
  }
}
